/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.jiadakeji.ppm.modules.business.service;

import com.jiadakeji.ppm.common.coderule.CodeRuleRecharge;
import com.jiadakeji.ppm.common.coderule.GetCode;
import com.jiadakeji.ppm.common.coderule.GetCodeByRule;
import com.jiadakeji.ppm.common.persistence.Page;
import com.jiadakeji.ppm.common.service.CrudService;
import com.jiadakeji.ppm.common.utils.DecimalUtils;
import com.jiadakeji.ppm.common.utils.StringUtils;
import com.jiadakeji.ppm.modules.business.dao.RechargeOrderDao;
import com.jiadakeji.ppm.modules.business.dao.RoomDao;
import com.jiadakeji.ppm.modules.business.entity.RechargeOrder;
import com.jiadakeji.ppm.modules.business.entity.Room;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 充值订单Service
 * @author HHAOYU
 * @version 2019-08-14
 */
@Service
@Transactional(readOnly = true)
public class RechargeOrderService extends CrudService<RechargeOrderDao, RechargeOrder> {
	@Autowired
	private RoomDao roomDao;

	@Override
	public RechargeOrder get(String id) {
		return super.get(id);
	}

	@Override
	public List<RechargeOrder> findList(RechargeOrder rechargeOrder) {
		return super.findList(rechargeOrder);
	}

	@Override
	public Page<RechargeOrder> findPage(Page<RechargeOrder> page, RechargeOrder rechargeOrder) {
		return super.findPage(page, rechargeOrder);
	}

	@Override
	@Transactional(readOnly = false,rollbackFor = Exception.class)
	public void save(RechargeOrder rechargeOrder) {
		if(StringUtils.isNotBlank(rechargeOrder.getId())){
			return;
		}else{
			Room room = roomDao.get(rechargeOrder.getRoomId());
			Double leftMoney = room.getBalance();
			if(null == leftMoney){
				leftMoney = 0.0;
			}
			if(null == rechargeOrder.getPayAmount()){
				rechargeOrder.setPayAmount(0.0);
			}
			rechargeOrder.setOrderStatus("0");
			GetCode getCode = new GetCodeByRule(new CodeRuleRecharge());
			rechargeOrder.setOrderCode(getCode.generateCode());
			room.setBalance(DecimalUtils.add(leftMoney,rechargeOrder.getPayAmount()));
			roomDao.update(room);
		}
		super.save(rechargeOrder);
	}


	@Override
	@Transactional(readOnly = false)
	public void delete(RechargeOrder rechargeOrder) {
		//TODO 删除其它关联表
		
		super.delete(rechargeOrder);
	}
	@Transactional(readOnly = false)
	public void changeChargeType(RechargeOrder rechargeOrder){
		RechargeOrder order = dao.get(rechargeOrder);
		if(null != order){
			if(order.getOrderType().equals(RechargeOrder.CHARGE_TYPE_CASH)){
				order.setOrderType(RechargeOrder.CHARGE_TYPE_WECHAT);
			}else if(order.getOrderType().equals(RechargeOrder.CHARGE_TYPE_WECHAT)){
				order.setOrderType(RechargeOrder.CHARGE_TYPE_CASH);
			}
			dao.update(order);
		}
	}

}